import { postMyEdituserinfo } from "@/api/siderBar/my"
import { useUserStore } from "@/stores"
import { message } from "ant-design-vue"

type FormState = {
    name?: string
}
export function useEditName(fn?: IFn) {
    const userStore = useUserStore()
    const { state: showName, on: openName, off: closeName } = useSwitch(false)
    const {
        clearValidate,
        formLoading,
        formRef,
        formState,
        rules,
        handleFormSubmit,
        resetFormState
    } = useFormState<FormState>({
        getInitialState() {
            return {}
        },
        rules: {
            name: {
                required: true
            }
        }
    })
    useEffectScope(() => {
        watch(showName, () => {
            if (showName.value === false) {
                clearValidate()
                resetFormState()
            }
        })
    })
    function triggerName(name?: string) {
        if (isSetValue(name)) {
            formState.value.name = name
        }
        openName()
    }
    async function handleSubmit() {
        await handleFormSubmit(values => {
            return postMyEdituserinfo({
                name: values.name!,
                gender: userStore.userInfo?.gender!,
                avatar: userStore.userInfo?.avatar,
                jobId: userStore.userInfo?.jobId,
                position: userStore.userInfo?.position,
                weChat: userStore.userInfo?.weChat
            })            
        })
        closeName()
        message.success("修改成功")
        fn?.()
    }
    return {
        formLoading,
        formState,
        rules,
        showName,
        triggerName,
        handleSubmit,
        formRef
    }
}